package JavaUtils.test_socket.demo03;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
 
/**
 * @Description:
 * @Author:          nicecloud
 * @CreateDate:      2019/6/29 22:56
 * @Version:         1.0
 */
public class UDPSearcher {
    public static void main(String[] args) throws IOException {
        System.out.println("UDPSearcher started.");
        // 作为搜索方，无需指定端口，系统自动分配
        DatagramSocket ds = new DatagramSocket(20000);
 
        // 构建一份回送数据
        String receiveData = "hello udp!";
        byte[] requestDataBytes = receiveData.getBytes();
        // 直接根据发送者构建一份回送信息
        DatagramPacket requestPacket = new DatagramPacket(requestDataBytes,
                requestDataBytes.length);
        // 本机端口20000
        requestPacket.setAddress(InetAddress.getLocalHost());
        requestPacket.setPort(20000);
 
        // 发送
        ds.send(requestPacket);
 
        // 构建接收实体
        final byte[] buf = new byte[512];
        DatagramPacket receivePacket = new DatagramPacket(buf, buf.length);
        // 接收
        ds.receive(receivePacket);
 
        // 打印接收到的信息与发送者的信息
        // 发送者的IP地址
        String ip = receivePacket.getAddress().getHostAddress();
        int port = receivePacket.getPort();
        int dataLen = receivePacket.getLength();
        String data = new String(receivePacket.getData(), 0, dataLen);
        System.out.println("UDPSearcher receive from ip:" + ip + "\tport:" + port + "\tdata:" + data);
 
        // 完成
        System.out.println("UDPSearcher Finished.");
        ds.close();
    }
}